package cn.gcyl.module.biz.controller.app;

import cn.gcyl.framework.common.exception.ServiceException;
import cn.gcyl.framework.common.pojo.CommonResult;
import cn.gcyl.framework.common.pojo.PageResult;
import cn.gcyl.framework.common.util.object.BeanUtils;
import cn.gcyl.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.gcyl.module.biz.controller.admin.aboutplatform.vo.AboutPlatformPageReqVO;
import cn.gcyl.module.biz.controller.admin.aboutplatform.vo.AboutPlatformRespVO;
import cn.gcyl.module.biz.controller.admin.collect.vo.CollectPageReqVO;
import cn.gcyl.module.biz.controller.admin.collect.vo.CollectRespVO;
import cn.gcyl.module.biz.controller.admin.collect.vo.CollectSaveReqVO;
import cn.gcyl.module.biz.controller.admin.conferenceinvoiceinformation.vo.AppConferenceInvoiceInformationSaveReqVO;
import cn.gcyl.module.biz.controller.admin.conferenceregistrationinformation.vo.AppJoinMeetingSaveReqVO;
import cn.gcyl.module.biz.controller.admin.conferenceregistrationinformation.vo.AppJoinOpenMembershipReqVO;
import cn.gcyl.module.biz.controller.admin.conferenceregistrationinformation.vo.ConferenceMeetingInformationPageReqVO;
import cn.gcyl.module.biz.controller.admin.conferenceregistrationinformation.vo.ConferenceRegistrationInformationSaveReqVO;
import cn.gcyl.module.biz.controller.admin.contactplatform.vo.ContactPlatformPageReqVO;
import cn.gcyl.module.biz.controller.admin.contactplatform.vo.ContactPlatformRespVO;
import cn.gcyl.module.biz.controller.admin.meetingplan.vo.MeetingPlanPageReqVO;
import cn.gcyl.module.biz.controller.admin.meetingplan.vo.MeetingPlanRespVO;
import cn.gcyl.module.biz.controller.admin.memberorder.vo.MemberOrderPageReqVO;
import cn.gcyl.module.biz.controller.admin.memberorder.vo.MemberOrderRespVO;
import cn.gcyl.module.biz.controller.admin.memberorder.vo.MemberOrderSaveReqVO;
import cn.gcyl.module.biz.controller.admin.membershipsettings.vo.MembershipSettingsPageReqVO;
import cn.gcyl.module.biz.controller.admin.membershipsettings.vo.MembershipSettingsRespVO;
import cn.gcyl.module.biz.controller.admin.platforminformation.vo.AppPlatformInformationListReqVO;
import cn.gcyl.module.biz.controller.admin.platformregistrationinformation.vo.AppPlatformUserRegistrationReqVO;
import cn.gcyl.module.biz.controller.admin.platformregistrationinformation.vo.PlatformRegistrationInformationSaveReqVO;
import cn.gcyl.module.biz.controller.admin.platformregistrationinformation.vo.PlatformUserRegistrationInformationPageReqVO;
import cn.gcyl.module.biz.controller.admin.privacy.vo.PrivacyPageReqVO;
import cn.gcyl.module.biz.controller.admin.privacy.vo.PrivacyRespVO;
import cn.gcyl.module.biz.controller.admin.specialmeeting.vo.AppSpecialMeetingListReqVO;
import cn.gcyl.module.biz.controller.admin.thirdpartyinformation.vo.AppThirdPartyInformationListReqVO;
import cn.gcyl.module.biz.controller.admin.useractionlog.vo.UserActionLogPageReqVO;
import cn.gcyl.module.biz.controller.admin.useractionlog.vo.UserActionLogRespVO;
import cn.gcyl.module.biz.controller.admin.useragreement.vo.UserAgreementPageReqVO;
import cn.gcyl.module.biz.controller.admin.useragreement.vo.UserAgreementRespVO;
import cn.gcyl.module.biz.controller.admin.usersubscriptionwordslog.vo.UserSubscriptionWordsLogPageReqVO;
import cn.gcyl.module.biz.controller.app.DTO.AppUserSubscriptionWordsVO;
import cn.gcyl.module.biz.dal.dataobject.*;
import cn.gcyl.module.biz.dal.dataobject.aboutplatform.AboutPlatformDO;
import cn.gcyl.module.biz.dal.dataobject.collect.CollectDO;
import cn.gcyl.module.biz.dal.dataobject.conferenceinvoiceinformation.ConferenceInvoiceInformationDO;
import cn.gcyl.module.biz.dal.dataobject.conferenceregistrationinformation.ConferenceRegistrationInformationDO;
import cn.gcyl.module.biz.dal.dataobject.conferenceregistrationinformation.ConferenceUserRegistrationInformationPO;
import cn.gcyl.module.biz.dal.dataobject.contactplatform.ContactPlatformDO;
import cn.gcyl.module.biz.dal.dataobject.meetingplan.MeetingPlanDO;
import cn.gcyl.module.biz.dal.dataobject.memberorder.MemberOrderDO;
import cn.gcyl.module.biz.dal.dataobject.membershipsettings.MembershipSettingsDO;
import cn.gcyl.module.biz.dal.dataobject.platforminformation.PlatformInformationDO;
import cn.gcyl.module.biz.dal.dataobject.platformregistrationinformation.PlatformRegistrationInformationDO;
import cn.gcyl.module.biz.dal.dataobject.platformregistrationinformation.PlatformUserRegistrationInformationPO;
import cn.gcyl.module.biz.dal.dataobject.privacy.PrivacyDO;
import cn.gcyl.module.biz.dal.dataobject.specialmeeting.SpecialMeetingDO;
import cn.gcyl.module.biz.dal.dataobject.thirdpartyinformation.ThirdPartyInformationDO;
import cn.gcyl.module.biz.dal.dataobject.useractionlog.UserActionLogDO;
import cn.gcyl.module.biz.dal.dataobject.useragreement.UserAgreementDO;
import cn.gcyl.module.biz.dal.mysql.SysMemberUserMapper;
import cn.gcyl.module.biz.dal.mysql.SysPayOrderMapper;
import cn.gcyl.module.biz.dal.mysql.aboutplatform.AboutPlatformMapper;
import cn.gcyl.module.biz.dal.mysql.collect.CollectMapper;
import cn.gcyl.module.biz.dal.mysql.conferenceregistrationinformation.ConferenceRegistrationInformationMapper;
import cn.gcyl.module.biz.dal.mysql.contactplatform.ContactPlatformMapper;
import cn.gcyl.module.biz.dal.mysql.meetingplan.MeetingPlanMapper;
import cn.gcyl.module.biz.dal.mysql.membershipsettings.MembershipSettingsMapper;
import cn.gcyl.module.biz.dal.mysql.platforminformation.PlatformInformationMapper;
import cn.gcyl.module.biz.dal.mysql.platformregistrationinformation.PlatformRegistrationInformationMapper;
import cn.gcyl.module.biz.dal.mysql.privacy.PrivacyMapper;
import cn.gcyl.module.biz.dal.mysql.specialmeeting.SpecialMeetingMapper;
import cn.gcyl.module.biz.dal.mysql.thirdpartyinformation.ThirdPartyInformationMapper;
import cn.gcyl.module.biz.dal.mysql.useractionlog.UserActionLogMapper;
import cn.gcyl.module.biz.dal.mysql.useragreement.UserAgreementMapper;
import cn.gcyl.module.biz.dal.mysql.usersubscriptionwordslog.UserSubscriptionWordsLogMapper;
import cn.gcyl.module.biz.service.aboutplatform.AboutPlatformService;
import cn.gcyl.module.biz.service.alliancemembers.AllianceMembersService;
import cn.gcyl.module.biz.service.carouselimage.CarouselImageService;
import cn.gcyl.module.biz.service.collect.CollectService;
import cn.gcyl.module.biz.service.conferenceinvoiceinformation.ConferenceInvoiceInformationService;
import cn.gcyl.module.biz.service.conferenceregistrationinformation.ConferenceRegistrationInformationService;
import cn.gcyl.module.biz.service.contactplatform.ContactPlatformService;
import cn.gcyl.module.biz.service.marketinformation.MarketInformationService;
import cn.gcyl.module.biz.service.meetingplan.MeetingPlanService;
import cn.gcyl.module.biz.service.memberorder.MemberOrderService;
import cn.gcyl.module.biz.service.membershipsettings.MembershipSettingsService;
import cn.gcyl.module.biz.service.platforminformation.PlatformInformationService;
import cn.gcyl.module.biz.service.platformregistrationinformation.PlatformRegistrationInformationService;
import cn.gcyl.module.biz.service.privacy.PrivacyService;
import cn.gcyl.module.biz.service.specialmeeting.SpecialMeetingService;
import cn.gcyl.module.biz.service.useractionlog.UserActionLogService;
import cn.gcyl.module.biz.service.useragreement.UserAgreementService;
import cn.gcyl.module.biz.service.usersubscriptionwordslog.UserSubscriptionWordsLogService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.druid.sql.visitor.functions.If;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static cn.gcyl.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.gcyl.framework.common.pojo.CommonResult.error;
import static cn.gcyl.framework.common.pojo.CommonResult.success;
import static cn.gcyl.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.gcyl.framework.common.util.servlet.ServletUtils.getClientIP;
import static cn.gcyl.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.gcyl.module.system.enums.ErrorCodeConstants.*;

@Tag(name = "app - 我的")
@RestController
@RequestMapping("/app/user")
@Validated
public class AppUserController {

    @Resource
    private CollectMapper collectMapper;
    @Resource
    private CollectService collectService;
    @Resource
    private AboutPlatformMapper aboutPlatformMapper;
    @Resource
    private ContactPlatformMapper contactPlatformMapper;
    @Resource
    private UserAgreementMapper userAgreementMapper;

    @Resource
    private PrivacyMapper privacyMapper;

    @Resource
    private SysMemberUserMapper sysMemberUserMapper;
    @Resource
    private ConferenceRegistrationInformationService conferenceRegistrationInformationService;
    @Resource
    private ConferenceRegistrationInformationMapper conferenceRegistrationInformationMapper;
    @Resource
    private PlatformRegistrationInformationService platformRegistrationInformationService;
    @Resource
    private PlatformRegistrationInformationMapper platformRegistrationInformationMapper;
    @Resource
    private MemberOrderService memberOrderService;
    @Resource
    private UserActionLogService userActionLogService;
    @Resource
    private MeetingPlanService meetingPlanService;
    @Resource
    private MeetingPlanMapper meetingPlanMapper;
    @Resource
    private ConferenceInvoiceInformationService conferenceInvoiceInformationService;
    @Resource
    private SysPayOrderMapper sysPayOrderMapper;
    @Resource
    private MembershipSettingsMapper membershipSettingsMapper;
    @Resource
    private UserSubscriptionWordsLogMapper subscriptionWordsLogMapper;
    @Resource
    private SpecialMeetingMapper specialMeetingMapper;
    @Resource
    private PlatformInformationMapper platformInformationMapper;
    @Resource
    private SpecialMeetingService specialMeetingService;
    @Resource
    private ThirdPartyInformationMapper thirdPartyInformationMapper;
    @Resource
    private PlatformInformationService platformInformationService;
    @Resource
    private MembershipSettingsService membershipSettingsService;
    @Resource
    private UserActionLogMapper userActionLogMapper;

    @GetMapping("/getUserIsMember")
    @Operation(summary = "判断用户是否为会员")
    public CommonResult<SysMemberUserViewPO> getUserIsMember() {
        Long userId = getLoginUserId();
        SysMemberUserViewPO po = new SysMemberUserViewPO();
        if (ObjectUtil.isNotEmpty(userId)) {
            SysMemberUserDO sysMemberUserDO = sysMemberUserMapper.selectById(userId);
            if (ObjectUtil.isEmpty(sysMemberUserDO)) {
                po.setIsMember(false);
                po.setIsValidityPeriodExpires(true);
                po.setIsNumberExpires(true);
                po.setViewingTime(null);
                return success(po);
            }

            LocalDateTime now = LocalDateTime.now();
            LocalDateTime purchaseDate = sysMemberUserDO.getMemberPurchaseDate();
            LocalDateTime expirationDate = sysMemberUserDO.getMemberExpirationDate();

            // 设置查看时间
            if (ObjectUtil.isNotEmpty(sysMemberUserDO.getViewingTime())) {
                po.setViewingTime(sysMemberUserDO.getViewingTime());
            }

            // 会员状态判断
            if (purchaseDate != null && expirationDate != null) {
                boolean isMember = !now.isBefore(purchaseDate) && !now.isAfter(expirationDate);
                po.setIsMember(isMember);
                po.setIsValidityPeriodExpires(now.isAfter(expirationDate));
            } else {
                po.setIsMember(false);
                po.setIsValidityPeriodExpires(true);
            }

            // 次数判断（根据实际字段调整）
            if (sysMemberUserDO.getRemainingConsultationFrequency() != null && sysMemberUserDO.getRemainingRegistrationsFrequency() != null) {
                po.setIsNumberExpires(sysMemberUserDO.getRemainingConsultationFrequency() <= 0);
            } else {
                po.setIsNumberExpires(true);
            }

            return success(po);
        }
        return success(po);
    }

    @GetMapping("/getUser")
    @Operation(summary = "获取app个人信息")
    public CommonResult<SysMemberUserInfoPO> getUser() {
        Long userId = getLoginUserId();
        if (ObjectUtil.isNotEmpty(userId)) {
            SysMemberUserDO sysMemberUserDO = sysMemberUserMapper.selectById(userId);
            SysMemberUserInfoPO bean = BeanUtils.toBean(sysMemberUserDO, SysMemberUserInfoPO.class);
            if (ObjectUtil.isNotEmpty(sysMemberUserDO.getMemberId()) &&sysMemberUserDO.getMemberId()!=0) {
                MembershipSettingsDO membershipSettingsDO = membershipSettingsMapper.selectById(sysMemberUserDO.getMemberId());
                bean.setMemberName(membershipSettingsDO.getMembershipName());
            }
            return success(bean);
        }
        return error(USER_NOT_LOGIN);
    }

    @PutMapping("/update")
    @Operation(summary = "更新个人信息")
    public CommonResult<Boolean> updateUser(@Valid @RequestBody MemberUserUpdateInfoReqVO updateReqVO) {
        Long userId = getLoginUserId();
        if (ObjectUtil.isNotEmpty(userId)) {
            SysMemberUserDO sysMemberUserDO = sysMemberUserMapper.selectById(userId);
            if (ObjectUtil.isNotEmpty(sysMemberUserDO)) {
                sysMemberUserDO.setNickname(updateReqVO.getNickname());
                sysMemberUserDO.setAvatar(updateReqVO.getAvatar());
                sysMemberUserMapper.updateById(sysMemberUserDO);
                return success(true);
            }
        }
        return success(false);
    }


    @PostMapping("/collectionOperation")
    @Operation(summary = "收藏操作")
    public CommonResult<String> createCollect(@Valid @RequestBody CollectSaveReqVO createReqVO) {
        Long loginUserId = getLoginUserId();
        if (ObjectUtil.isEmpty(loginUserId)) {
            throw new ServiceException(USER_NOT_LOGIN);
        }

        if (createReqVO.getId() == null) {
            throw new ServiceException(COLLECT_NOT_EXISTS);
        }

        String userIdStr = String.valueOf(loginUserId);

        if (createReqVO.getModule().equals("专场会议")) {
            SpecialMeetingDO specialMeetingDO = specialMeetingMapper.selectById(createReqVO.getId());
            if (ObjectUtil.isNotEmpty(specialMeetingDO)) {
            String userCollectIds = specialMeetingDO.getUserCollectIds();
            userCollectIds = updateUserIds(userCollectIds, userIdStr, createReqVO.getStatus());
            specialMeetingDO.setUserCollectIds(userCollectIds);
            specialMeetingMapper.updateById(specialMeetingDO);
            if (createReqVO.getStatus() == 1) {
                CollectSaveReqVO collectSaveReqVO = new CollectSaveReqVO();
                collectSaveReqVO.setUserId(loginUserId);
                collectSaveReqVO.setModule(createReqVO.getModule());
                collectSaveReqVO.setTitle(specialMeetingDO.getMeetingName());
                Long collect = collectService.createCollect(collectSaveReqVO);

                // 添加操作日志
                UserActionLogDO userActionLogDO = new UserActionLogDO();
                userActionLogDO.setUserId(getLoginUserId());
                userActionLogDO.setAction("收藏:"+specialMeetingDO.getMeetingName());
                userActionLogMapper.insert(userActionLogDO);
            }
        }
            return success("收藏成功");

        } else if (createReqVO.getModule().equals("项目采购商机") ||
                createReqVO.getModule().equals("项目分包商机") ||
                createReqVO.getModule().equals("集中招募商机")) {
            PlatformInformationDO platformInformationDO = platformInformationMapper.selectById(createReqVO.getId());
            if (ObjectUtil.isNotEmpty(platformInformationDO)) {

                String userCollectIds = platformInformationDO.getUserCollectIds();
                userCollectIds = updateUserIds(userCollectIds, userIdStr, createReqVO.getStatus());
                platformInformationDO.setUserCollectIds(userCollectIds);
                platformInformationMapper.updateById(platformInformationDO);
                if (createReqVO.getStatus() == 1) {
                    CollectSaveReqVO collectSaveReqVO = new CollectSaveReqVO();
                    collectSaveReqVO.setUserId(loginUserId);
                    collectSaveReqVO.setModule(createReqVO.getModule());
                    collectSaveReqVO.setTitle(platformInformationDO.getTitle());
                    Long collect = collectService.createCollect(collectSaveReqVO);

                    // 添加操作日志
                    UserActionLogDO userActionLogDO = new UserActionLogDO();
                    userActionLogDO.setUserId(getLoginUserId());
                    userActionLogDO.setAction("收藏:" + platformInformationDO.getTitle());
                    userActionLogMapper.insert(userActionLogDO);
                }
            }
            return success("收藏成功");

        } else if (createReqVO.getModule().equals("招标") ||
                createReqVO.getModule().equals("采购") ||
                createReqVO.getModule().equals("中标")) {
            ThirdPartyInformationDO thirdPartyInformationDO = thirdPartyInformationMapper.selectById(createReqVO.getId());
            if (ObjectUtil.isNotEmpty(thirdPartyInformationDO)) {
                String userCollectIds = thirdPartyInformationDO.getUserCollectIds();
                userCollectIds = updateUserIds(userCollectIds, userIdStr, createReqVO.getStatus());
                thirdPartyInformationDO.setUserCollectIds(userCollectIds);
                thirdPartyInformationMapper.updateById(thirdPartyInformationDO);
                if (createReqVO.getStatus() == 1) {
                    CollectSaveReqVO collectSaveReqVO = new CollectSaveReqVO();
                    collectSaveReqVO.setUserId(loginUserId);
                    collectSaveReqVO.setModule(createReqVO.getModule());
                    collectSaveReqVO.setTitle(thirdPartyInformationDO.getTitle());
                    Long collect = collectService.createCollect(collectSaveReqVO);
                    // 添加操作日志
                    UserActionLogDO userActionLogDO = new UserActionLogDO();
                    userActionLogDO.setUserId(getLoginUserId());
                    userActionLogDO.setAction("收藏:" + thirdPartyInformationDO.getTitle());
                    userActionLogMapper.insert(userActionLogDO);
                }
            }
            return success("收藏成功");
        }

        throw new ServiceException(COLLECT_NOT_EXISTS);
    }

    /**
     * 更新用户ID列表
     * @param userIds 原始用户ID字符串
     * @param userId 当前用户ID
     * @param status 操作状态：0-移除，1-添加
     * @return 更新后的用户ID字符串
     */
    private String updateUserIds(String userIds, String userId, Integer status) {
        Set<String> userIdSet = new HashSet<>();

        // 解析现有的用户ID
        if (ObjectUtil.isNotEmpty(userIds)) {
            String[] ids = userIds.split(",");
            for (String id : ids) {
                if (ObjectUtil.isNotEmpty(id.trim())) {
                    userIdSet.add(id.trim());
                }
            }
        }

        // 根据状态添加或移除用户ID
        if (status == 1) {
            // 添加用户ID
            userIdSet.add(userId);
        } else if (status == 0) {
            // 移除用户ID
            userIdSet.remove(userId);
        }

        // 重新构建用户ID字符串
        if (CollUtil.isEmpty(userIdSet)) {
            return "";
        }

        return String.join(",", userIdSet);
    }

    @GetMapping("/getUserCollect")
    @Operation(summary = "我的收藏")
    public CommonResult<PageResult<AppUserSubscriptionWordsVO>> getUserCollect(@Valid UserSubscriptionWordsLogPageReqVO reqVO) {
        Long userId = getLoginUserId();
        if (ObjectUtil.isNotEmpty(userId)) {
            if (reqVO.getColumns().equals("项目采购商机") || reqVO.getColumns().equals("项目分包商机") || reqVO.getColumns().equals("集中招募商机")) {
                AppPlatformInformationListReqVO platformInformationListReqVO = new AppPlatformInformationListReqVO();
                platformInformationListReqVO.setTitleType(reqVO.getColumns());
                PageResult<PlatformInformationDO> platformInformationDOPageResult = platformInformationService.AppPlatformInformationListReqVO(platformInformationListReqVO);
                PageResult<AppUserSubscriptionWordsVO> bean = BeanUtils.toBean(platformInformationDOPageResult, AppUserSubscriptionWordsVO.class);
                return success(bean);
            } else if (reqVO.getColumns().equals("专场会议")) {
                AppSpecialMeetingListReqVO appSpecialMeetingListReqVO = new AppSpecialMeetingListReqVO();
                PageResult<SpecialMeetingDO> appSpecialMeetingList = specialMeetingMapper.getAppSpecialMeetingList(appSpecialMeetingListReqVO);
                PageResult<AppUserSubscriptionWordsVO> bean = BeanUtils.toBean(appSpecialMeetingList, AppUserSubscriptionWordsVO.class);
                for (AppUserSubscriptionWordsVO appUserSubscriptionWordsVO : bean.getList()) {
                    // 根据开始时间和结束时间设置会议状态
                    LocalDateTime now = LocalDateTime.now();
                    if (now.isBefore(appUserSubscriptionWordsVO.getStartTime())) {
                        // 当前时间在开始时间之前，会议未开始
                        appUserSubscriptionWordsVO.setActiveState(0);
                    } else if (now.isAfter(appUserSubscriptionWordsVO.getEndTime())) {
                        // 当前时间在结束时间之后，会议已结束
                        appUserSubscriptionWordsVO.setActiveState(2);
                    } else {
                        // 当前时间在开始时间和结束时间之间，会议进行中
                        appUserSubscriptionWordsVO.setActiveState(1);
                    }
                }
                return success(bean);
            } else if (reqVO.getColumns().equals("招标") || reqVO.getColumns().equals("采购") || reqVO.getColumns().equals("中标")) {
                AppThirdPartyInformationListReqVO appThirdPartyInformationListReqVO = new AppThirdPartyInformationListReqVO();
                PageResult<ThirdPartyInformationDO> appThirdPartyInformationList = thirdPartyInformationMapper.getAppThirdPartyInformationList(appThirdPartyInformationListReqVO);
                PageResult<AppUserSubscriptionWordsVO> bean = BeanUtils.toBean(appThirdPartyInformationList, AppUserSubscriptionWordsVO.class);
                return success(bean);
            }
        }
        return success(null);
    }


    @GetMapping("/getMeetingListPage")
    @Operation(summary = "获得用户会议报名信息分页")
    public CommonResult<PageResult<ConferenceUserRegistrationInformationPO>>
    getMeetingListPage(@Valid ConferenceMeetingInformationPageReqVO pageVO) {
        pageVO.setUserId(getLoginUserId());
        PageResult<ConferenceUserRegistrationInformationPO> meetingListPage =
                conferenceRegistrationInformationService.getMeetingListPage(pageVO);
        return success(meetingListPage);
    }

    @GetMapping("/getMeetingListIsView")
    @Operation(summary = "判断用户会议报名信息是否已查看")
    public CommonResult<Map<String, Boolean>> getMeetingListIsView() {
        Long loginUserId = getLoginUserId();
        Map<String, Boolean> result = new HashMap<>();

        if (ObjectUtil.isEmpty(loginUserId)) {
            result.put("待审核", false);
            result.put("已通过", false);
            result.put("已驳回", false);
            return success(result);
        }

        // 查询所有该用户的会议报名信息
        List<ConferenceRegistrationInformationDO> allRegistrations = conferenceRegistrationInformationMapper.selectList(
                new LambdaQueryWrapperX<ConferenceRegistrationInformationDO>()
                        .eqIfPresent(ConferenceRegistrationInformationDO::getUserId, loginUserId)
                        .eqIfPresent(ConferenceRegistrationInformationDO::getIsView, 0)
        );

        // 按isFree字段分组并检查每组是否有数据
        boolean hasIsFree0 = allRegistrations.stream()
                .anyMatch(registration -> registration.getIsFree() != null && registration.getIsFree() == 0);

        boolean hasIsFree1 = allRegistrations.stream()
                .anyMatch(registration -> registration.getIsFree() != null && registration.getIsFree() == 1);

        boolean hasIsFree2 = allRegistrations.stream()
                .anyMatch(registration -> registration.getIsFree() != null && registration.getIsFree() == 2);

        result.put("待审核", hasIsFree0);
        result.put("已通过", hasIsFree1);
        result.put("已驳回", hasIsFree2);

        return success(result);
    }
    @GetMapping("/getMeetingListIsViewStatus")
    @Operation(summary = "操作用户会议报名是否查看")
    public CommonResult<Boolean> getMeetingListIsViewStatus(@Valid ConferenceMeetingInformationPageReqVO pageVO) {
        Long loginUserId = getLoginUserId();
        if (ObjectUtil.isNotEmpty(loginUserId)) {
            if (pageVO.getIsFree()==0){
                List<ConferenceRegistrationInformationDO> conferenceRegistrationInformationDOS = conferenceRegistrationInformationMapper.selectList(
                        new LambdaQueryWrapperX<ConferenceRegistrationInformationDO>()
                                .eqIfPresent(ConferenceRegistrationInformationDO::getUserId, loginUserId)
                                .eqIfPresent(ConferenceRegistrationInformationDO::getIsFree, 0)
                );
                for (ConferenceRegistrationInformationDO conferenceRegistrationInformationDO : conferenceRegistrationInformationDOS) {
                    conferenceRegistrationInformationDO.setIsView(1);
                    conferenceRegistrationInformationMapper.updateById(conferenceRegistrationInformationDOS);
                }
            }
            if (pageVO.getIsFree() == 1 ) {
                List<ConferenceRegistrationInformationDO> conferenceRegistrationInformationDOS = conferenceRegistrationInformationMapper.selectList(
                        new LambdaQueryWrapperX<ConferenceRegistrationInformationDO>()
                                .eqIfPresent(ConferenceRegistrationInformationDO::getUserId,loginUserId)
                                .eqIfPresent(ConferenceRegistrationInformationDO::getIsFree, 1)
                );
                for (ConferenceRegistrationInformationDO conferenceRegistrationInformationDO : conferenceRegistrationInformationDOS) {
                    conferenceRegistrationInformationDO.setIsView(1);
                    conferenceRegistrationInformationMapper.updateById(conferenceRegistrationInformationDOS);
                }

            }
            if (pageVO.getIsFree() == 2 ) {
                List<ConferenceRegistrationInformationDO> conferenceRegistrationInformationDOS = conferenceRegistrationInformationMapper.selectList(
                        new LambdaQueryWrapperX<ConferenceRegistrationInformationDO>()
                                .eqIfPresent(ConferenceRegistrationInformationDO::getUserId, loginUserId)
                                .eqIfPresent(ConferenceRegistrationInformationDO::getIsFree, 2)
                );
                for (ConferenceRegistrationInformationDO conferenceRegistrationInformationDO : conferenceRegistrationInformationDOS) {
                    conferenceRegistrationInformationDO.setIsView(1);
                    conferenceRegistrationInformationMapper.updateById(conferenceRegistrationInformationDOS);
                }

            }
//                if (pageReqVO.getIsFree() == 3 && ObjectUtil.isNotEmpty(pageReqVO.getIsFree())) {
//                    List<ConferenceRegistrationInformationDO> conferenceRegistrationInformationDOS = conferenceRegistrationInformationMapper.selectList(
//                            new LambdaQueryWrapperX<ConferenceRegistrationInformationDO>()
//                                    .eqIfPresent(ConferenceRegistrationInformationDO::getUserId, loginUser.getId())
//                    );
//                    for (ConferenceRegistrationInformationDO conferenceRegistrationInformationDO : conferenceRegistrationInformationDOS) {
//                        conferenceRegistrationInformationDO.setIsView(1);
//                        conferenceRegistrationInformationMapper.updateById(conferenceRegistrationInformationDOS);
//                    }
//
//                }
        }

        return success(true);
    }
    @GetMapping("/getConferenceRegistrationByUserId")
    @Operation(summary = "获得会议报名信息ByUserId")
    public CommonResult<ConferenceUserRegistrationInformationPO> getConferenceRegistrationInformation(@RequestParam("id") Long id) {
        ConferenceUserRegistrationInformationPO meetingInfo = conferenceRegistrationInformationService.getMeetingInfo(id);
        return success(meetingInfo);
    }

    @GetMapping("/getUserPlatformInformationPage")
    @Operation(summary = "获得平台报名信息分页")
    public CommonResult<PageResult<PlatformUserRegistrationInformationPO>> getPlatformRegistrationInformationPage(
            @Valid PlatformUserRegistrationInformationPageReqVO pageReqVO) {
        Long loginUserId = getLoginUserId();
        if (ObjectUtil.isNotEmpty(loginUserId)) {
            pageReqVO.setUserId(loginUserId);
            PageResult<PlatformUserRegistrationInformationPO> pageResult =
                    platformRegistrationInformationService.getUserPlatformRegistrationInformationPage(pageReqVO);
            return success(pageResult);
        }
        return error(USER_NOT_LOGIN);
    }

    @GetMapping("/getPlatformRegistrationUserInfo")
    @Operation(summary = "获得平台报名信息详情")
    public CommonResult<PlatformUserRegistrationInformationPO> getPlatformRegistrationUserInfo(
            @Valid PlatformUserRegistrationInformationPageReqVO pageReqVO) {
        Long loginUserId = getLoginUserId();
        if (ObjectUtil.isNotEmpty(loginUserId)){
            pageReqVO.setUserId(loginUserId);
        }
        PlatformUserRegistrationInformationPO platformRegistrationInformationOne = platformRegistrationInformationService.getPlatformRegistrationInformationOne(pageReqVO);
        return success(platformRegistrationInformationOne);
    }
    @GetMapping("/getPlatformRegistrationUserIsView")
    @Operation(summary = "获得用户平台报名是否查看")
    public CommonResult<Boolean> getPlatformRegistrationUserIsView() {
        Long loginUserId = getLoginUserId();
        Boolean isView = false;
        if (ObjectUtil.isNotEmpty(loginUserId)) {
            List<PlatformRegistrationInformationDO> platformRegistrationInformationDOS = platformRegistrationInformationMapper.selectList(
                    new LambdaQueryWrapper<PlatformRegistrationInformationDO>().eq(PlatformRegistrationInformationDO::getUserId, loginUserId)
            );
            for (PlatformRegistrationInformationDO platformRegistrationInformationDO : platformRegistrationInformationDOS) {
                if (platformRegistrationInformationDO.getIsView() == 0) {
                    isView = true;
                }
            }
        }
        return success(isView);
    }

    @GetMapping("/getUserActionLogPage")
    @Operation(summary = "获得用户操作日志分页")
    public CommonResult<PageResult<UserActionLogRespVO>> getUserActionLogPage(@Valid UserActionLogPageReqVO pageReqVO) {
        PageResult<UserActionLogDO> pageResult = userActionLogService.getUserActionLogPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, UserActionLogRespVO.class));
    }

    @GetMapping("/getAboutPlatformPage")
    @Operation(summary = "关于平台")
    @PermitAll
    public CommonResult<List<AboutPlatformDO>> getAboutPlatformPage() {
        return success(aboutPlatformMapper.selectList());
    }

    @GetMapping("/getContactPlatformPage")
    @Operation(summary = "联系平台")
    @PermitAll
    public CommonResult<List<ContactPlatformDO>> getContactPlatformPage() {
        return success(contactPlatformMapper.selectList());
    }

    @GetMapping("/getUserAgreementPage")
    @Operation(summary = "获得用户协议分页")
    @PermitAll
    public CommonResult<List<UserAgreementDO>> getUserAgreementPage() {
        return success(userAgreementMapper.selectList());
    }

    @GetMapping("/getPrivacyPage")
    @Operation(summary = "获得隐私政策分页")
    @PermitAll
    public CommonResult<List<PrivacyDO>> getPrivacyPage() {
        List<PrivacyDO> privacyDOS = privacyMapper.selectList();
        return success(privacyDOS);
    }

    @GetMapping("/getMeetingPlanListById")
    @Operation(summary = "获得参会方案By会议id")
    public CommonResult<List<MeetingPlanDO>> getMeetingPlanListById(@Valid MeetingPlanPageReqVO pageReqVO) {
        // 检查参数
        if (pageReqVO == null || pageReqVO.getMeetingId() == null) {
            return success(new ArrayList<>());
        }
        SpecialMeetingDO specialMeetingDO = specialMeetingMapper.selectById(pageReqVO.getMeetingId());
        // 检查会议是否存在
        if (ObjectUtil.isEmpty(specialMeetingDO)) {
            return success(new ArrayList<>());
        }
        // 检查是否有参会方案
        String meetingPlanIdStr = specialMeetingDO.getMeetingPlanId();
        if (ObjectUtil.isEmpty(meetingPlanIdStr)) {
            return success(new ArrayList<>());
        }

        try {
            // 将逗号分隔的字符串转换为ID列表
            List<Long> meetingPlanIds = Arrays.stream(meetingPlanIdStr.split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .map(Long::valueOf)
                    .filter(id -> id > 0) // 确保ID是正数
                    .collect(Collectors.toList());

            // 如果没有有效的ID，则返回空列表
            if (CollUtil.isEmpty(meetingPlanIds)) {
                return success(new ArrayList<>());
            }

            // 查询参会方案
            List<MeetingPlanDO> meetingPlanDOS = meetingPlanMapper.selectList(
                    new LambdaQueryWrapper<MeetingPlanDO>()
                            .in(MeetingPlanDO::getId, meetingPlanIds)
            );
            return success(meetingPlanDOS);
        } catch (NumberFormatException e) {
            // 处理ID格式错误的情况
            return success(new ArrayList<>());
        }
    }
    @GetMapping("/getMeetingPlanList")
    @Operation(summary = "获得参会方案分页")
    public CommonResult<PageResult<MeetingPlanRespVO>> getMeetingPlanList(@Valid MeetingPlanPageReqVO pageReqVO) {
        PageResult<MeetingPlanDO> pageResult = meetingPlanService.getMeetingPlanPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, MeetingPlanRespVO.class));
    }


    @PostMapping("/join-meeting")
    @Operation(summary = "app - 用户参加会议")
    public CommonResult<ConferenceRegistrationInformationDO> getMeetingListPage(@RequestBody AppJoinMeetingSaveReqVO saveReqVO) {
        ConferenceRegistrationInformationDO conferenceRegistrationInformationDO = conferenceRegistrationInformationService.getMeetingInfoByUserId(saveReqVO.getMeetingId(), getLoginUserId());
        if (ObjectUtil.isNotEmpty(conferenceRegistrationInformationDO)){
            throw exception(NOT_CAN_JOIN_MEETING);
        }

        List<MeetingPlanDO> meetingPlanDOS = new ArrayList<>(); // 默认为空列表

        // 只有当meetingPlanIds不为空时才查询
        if (saveReqVO.getMeetingPlanIds() != null && !saveReqVO.getMeetingPlanIds().isEmpty()) {
            meetingPlanDOS = meetingPlanService.getMeetingPlanByIds(saveReqVO.getMeetingPlanIds());
        }

        // 注意：这里不再检查meetingPlanDOS是否为空，因为可能传空的meetingPlanIds

        BigDecimal total = BigDecimal.ZERO;
        for (MeetingPlanDO planDO : meetingPlanDOS) {
            if (planDO != null && planDO.getSchemePrice() != null) {
                total = total.add(planDO.getSchemePrice());
            }
        }

        ConferenceRegistrationInformationDO registrationInformationDO = BeanUtils.toBean(saveReqVO, ConferenceRegistrationInformationDO.class);
        registrationInformationDO.setJoinAmount(total);
        String orderNo = String.valueOf(IdUtil.getSnowflakeNextId());
        registrationInformationDO.setOrderNo(orderNo);

        if (saveReqVO.getJoinType() == 1){
            // 创建会议支付订单
            BigDecimal totalFen = total.multiply(new BigDecimal("100"));
            // TODO 创建支付订单发起支付
            SysPayOrderDO payOrderDO = new SysPayOrderDO().setUserIp(getClientIP()).setMerchantOrderId(orderNo).setAppId(1L).
                    setPrice(totalFen.intValue()).setExpireTime(LocalDateTime.now().plusMinutes(10)).setBody("参加会议：" + saveReqVO.getMeetingId())
                    .setSubject("参加会议").setNotifyUrl("https://gcyl.chinep.net/gcyl/app-api/callback/pay").setStatus(0).setRefundPrice(0);
            sysPayOrderMapper.insert(payOrderDO);

            registrationInformationDO.setPayOrderId(payOrderDO.getId());
            conferenceRegistrationInformationService.createConferenceRegistrationInformationDO(registrationInformationDO);
        } else if (saveReqVO.getJoinType() == 2){
            conferenceRegistrationInformationService.createConferenceRegistrationInformationDO(registrationInformationDO);
        } else {
            registrationInformationDO.setPayStatus(1);
            registrationInformationDO.setIsFree(1);
            conferenceRegistrationInformationService.createConferenceRegistrationInformationDO(registrationInformationDO);
        }

        // 创建发票信息
        AppConferenceInvoiceInformationSaveReqVO appConferenceInvoiceInformationSaveReqVO = saveReqVO.getAppConferenceInvoiceInformationSaveReqVO();
        if (appConferenceInvoiceInformationSaveReqVO != null) {
            appConferenceInvoiceInformationSaveReqVO.setConferenceRegistrationId(registrationInformationDO.getId());
            ConferenceInvoiceInformationDO invoiceInformationDO = BeanUtils.toBean(appConferenceInvoiceInformationSaveReqVO, ConferenceInvoiceInformationDO.class);
            conferenceInvoiceInformationService.createConferenceInvoiceInformationDO(invoiceInformationDO);
        }

        // 添加操作日志
        UserActionLogDO userActionLogDO = new UserActionLogDO();
        userActionLogDO.setUserId(getLoginUserId());
        userActionLogDO.setAction("报名会议:"+saveReqVO.getMeetingId());
        userActionLogMapper.insert(userActionLogDO);

        return success(registrationInformationDO);
    }

    @GetMapping("/getMembershipSettingsList")
    @Operation(summary = "获得会员设置list")
    public CommonResult<List<MembershipSettingsRespVO>> getMembershipSettingsList(@Valid MembershipSettingsPageReqVO pageReqVO) {
        List<MembershipSettingsDO> membershipSettingsList = membershipSettingsService.getMembershipSettingsList(pageReqVO);
        return success(BeanUtils.toBean(membershipSettingsList, MembershipSettingsRespVO.class));
    }

    @PostMapping("/openMembership")
    @Operation(summary = "app - 用户开通会员")
    @Transactional
    public CommonResult<MemberOrderSaveReqVO> OpenMembership(@RequestBody AppJoinOpenMembershipReqVO saveReqVO) {
        Long loginUserId = getLoginUserId();
        LocalDateTime now = LocalDateTime.now();
        if (ObjectUtil.isNotEmpty(loginUserId)) {
            SysMemberUserDO sysMemberUserDO = sysMemberUserMapper.selectById(loginUserId);
            // 检查用户是否存在
            if (ObjectUtil.isEmpty(sysMemberUserDO)) {
                throw exception(USER_NOT_EXISTS);
            }
            MembershipSettingsDO membershipSettingsDO = membershipSettingsMapper.selectById(saveReqVO.getMemberId());
            if (ObjectUtil.isEmpty(membershipSettingsDO)) {
                throw exception(MEMBERSHIP_SETTINGS_NOT_EXISTS);
            }
            // 获取购买数量，默认为1，将Long转换为Integer
            Integer number = 1;
            if (saveReqVO.getNumber() != null) {
                number = saveReqVO.getNumber().intValue();
            }
            // 计算总价
            BigDecimal total = membershipSettingsDO.getPrice().multiply(BigDecimal.valueOf(number));
            String orderNo = String.valueOf(IdUtil.getSnowflakeNextId());

            // 创建支付订单
            BigDecimal totalFen = total.multiply(new BigDecimal("100"));
            SysPayOrderDO payOrderDO = new SysPayOrderDO()
                    .setUserIp(getClientIP())
                    .setMerchantOrderId(orderNo)
                    .setAppId(1L)
                    .setPrice(totalFen.intValue())
                    .setExpireTime(LocalDateTime.now().plusMinutes(10))
                    .setBody("用户：" + (sysMemberUserDO.getNickname() != null ? sysMemberUserDO.getNickname() : "") + "开通会员：")
                    .setSubject(membershipSettingsDO.getMembershipName() != null ? membershipSettingsDO.getMembershipName() : "")
                    .setNotifyUrl("https://gcyl.chinep.net/gcyl/app-api/callback/memberPay").setStatus(0).setRefundPrice(0);
            // 检查支付订单是否创建成功
            if (sysPayOrderMapper.insert(payOrderDO) <= 0) {
                throw exception(PAY_ORDER_CREATE_FAILED);
            }

            // 添加操作日志
            UserActionLogDO userActionLogDO = new UserActionLogDO();
            userActionLogDO.setUserId(getLoginUserId());
            userActionLogDO.setAction("购买会员:"+membershipSettingsDO.getMembershipName() + "，数量：" + number);
            userActionLogMapper.insert(userActionLogDO);

            // 添加会员订单记录
            MemberOrderSaveReqVO memberOrderSaveReqVO = new MemberOrderSaveReqVO();
            memberOrderSaveReqVO.setNumber(number);
            memberOrderSaveReqVO.setMembershipName(membershipSettingsDO.getMembershipName());
            memberOrderSaveReqVO.setPaymentAmount(total); // 使用计算后的总价
            memberOrderSaveReqVO.setUserId(sysMemberUserDO.getId());
            memberOrderSaveReqVO.setMobile(sysMemberUserDO.getMobile());
            memberOrderSaveReqVO.setNickname(sysMemberUserDO.getNickname());
            // 格式化时间显示
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            memberOrderSaveReqVO.setEffectiveTime(now.format(formatter) + "," + now.plusDays(membershipSettingsDO.getLifeSpan() * number).format(formatter));
            memberOrderSaveReqVO.setPayOrderId(payOrderDO.getId());
            memberOrderSaveReqVO.setOrderNo(orderNo);
            memberOrderSaveReqVO.setTotalAmount(total);
            memberOrderService.createMemberOrder(memberOrderSaveReqVO);

            return success(memberOrderSaveReqVO);
        }
        throw exception(USER_NOT_LOGIN);
    }

    @PostMapping("/platform-registration")
    @Operation(summary = "app - 用户平台报名")
    public CommonResult<String> platformRegistration(@Valid @RequestBody AppPlatformUserRegistrationReqVO createReqVO) {
        createReqVO.setUserId(getLoginUserId());
        Long appPlatformRegistrationInformation = platformRegistrationInformationService.createAppPlatformRegistrationInformation(createReqVO);
        if (appPlatformRegistrationInformation==0){
            return error(0,"报名失败");
        }
        return success("报名成功");
    }

    @GetMapping("/platform-consult")
    @Operation(summary = "app - 用户平台咨询")
    @Parameter(name = "id", description = "平台信息id", required = true)
    public CommonResult<PlatformInformationDO> platformConsult(@RequestParam("id") Long id) {
        return success(platformRegistrationInformationService.createAppPlatformConsult(id));
    }


}
